<?php

session_start();
require 'connection.php';

$app = new \Slim\Slim();
$app->get('/config/:id', authorize('admin'), 'read');
$app->put('/config/:id', authorize('admin'), 'edit');

$app->run();

function read($id) {
    $sql_read = "SELECT * FROM config WHERE id = :id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql_read);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $rst = $stmt->fetchObject();
        $db = null;
        echo json_encode($rst);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}

function edit($id) {
    $sql_edit = "UPDATE config SET 
        company_name = :company_name, 
        company_ruc = :company_ruc, 
        company_address = :company_address, 
        tax = :tax, 
        current_year = :current_year, 
        current_month = :current_month 
        WHERE id = :id";
    $request = \Slim\Slim::getInstance()->request();
    $body = $request->getBody();
    $param = json_decode($body);
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql_edit);
        $stmt->bindParam("company_name", $param->company_name);
        $stmt->bindParam("company_ruc", $param->company_ruc);
        $stmt->bindParam("company_address", $param->company_address);
        $stmt->bindParam("tax", $param->tax);
        $stmt->bindParam("current_year", $param->current_year);
        $stmt->bindParam("current_month", $param->current_month);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $_SESSION['company_name'] = $param->company_name;
        $_SESSION['company_ruc'] = $param->company_ruc;
        $_SESSION['company_address'] = $param->company_address;
        $_SESSION['tax'] = $param->company_name;
        $_SESSION['current_year'] = $param->current_year;
        $_SESSION['current_month'] = $param->current_month;
        $db = null;
        
                
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}

?>